

#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <thread>
#include <cstring>
#include "utilitys.h"

template <class T>
T *CreateProdSharMemory(int nKey, int &shmID)

{
    // 创建共享内存
    shmID = shmget(nKey, SHARED_MEMORY_SIZE, 0666 | IPC_CREAT);
    if (shmID < 0)
    {
        // todo 输出log 共享内存创建失败
        std::cerr << "shmget fail, " << errno << std::endl;
        return nullptr;
    }

    // 映射共享内存到进程地址空间
    T *pDataField = (T *)shmat(shmID, 0, 0);
    if (((void *)(-1)) == (void *)pDataField)
    {
        // 映射失败
        std::cerr << "shmat failed: " << errno << std::endl;
        perror("shmat ");
        return nullptr;
    }

    // 映射成功
    return pDataField;
}

int main()
{
    int shmID = 0;
    SharedMemory *pDataField = CreateProdSharMemory<SharedMemory>(333, shmID);
    pDataField->WriteIndex = 0;
    pDataField->Ready = false;
    long nWriteIndex = pDataField->WriteIndex;
    long nMaxWriteIndex = DATA_ARRAY_MAX_LENGTH - 1;
    DroneTradeDataRequestMessageField data;

    while (!pDataField->Ready)
    {
    }

    while (true)
    {
        ++nWriteIndex;
        nWriteIndex &= nMaxWriteIndex;
        data.droneTradeId++;
        std::memcpy(&pDataField->DataArray[nWriteIndex], &data, sizeof(DroneTradeDataRequestMessageField));
        pDataField->WriteIndex = nWriteIndex;

        std::this_thread::sleep_for(std::chrono::milliseconds(4));
    }

    return 0;
}